package com.techbrand.lb7.web.validator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

public class ZipCodeValidator implements Validator {

	@SuppressWarnings("rawtypes")
	public boolean supports(Class clazz) {
		return String.class.isAssignableFrom(clazz);
	}
	
	public void validate(Object obj, Errors errors) {
		String zipCode = (String) obj;
		
		if (zipCode != null && !zipCode.trim().isEmpty()) {
			Pattern pattern = Pattern.compile("\\d{4}");
			Matcher matcher = pattern.matcher(zipCode);
			
			if (!matcher.matches()) {
				errors.rejectValue("zipCode", "zipCode.invalid");
			}
		}
	}
}
